import global from '@/plugins/global'

let base = global.BACKEND_URL
let token
let tokenTest =
	"eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJlbWMtbWVkaWNhbC1zZXJ2ZXIiLCJzdWIiOiJmYW5xeiIsImF1ZCI6Im1vYmlsZSIsImlhdCI6MTYxMTk3MjUwMiwiZXhwIjoxNjEyMTQ1MzAyfQ.5LKfcs4PTqkO5zoIfhen0xR-UNj421HfuZmagLfZrF0UlmSRzPt_g27CPs25XnslwS3zEv8LY66FZn2I9MlstA";

const returnFail = (res) => {
	console.log(res,'报错')
	let content
	let code = res.code
	if (res.msg || res.msg == null) {
		content = res.msg
	} else {
		content = '网络波动'
	}
	
	if(res.code == 'A00995')return false
	if (res.code == 207) {
		uni.showModal({
			title: '提示',
			confirmText: "确定",
			content: content,
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					// 如果token过期则强制跳转到登录页面
					if (code === 'A00401') {
						uni.reLaunch({
							url:'/pages/login/wechatEntry'
						})
					}
					uni.hideLoading();
					console.log('用户点击确定');
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	} else {
		uni.showModal({
			title: '提示',
			confirmText: "确定",
			content: content,
			showCancel: false,
			success: (ress) => {
				if (ress.confirm) {
					// 如果token过期则强制跳转到登录页面
					if (res.code === 'A00401') {
						uni.reLaunch({
							url:'/pages/login/wechatEntry'
						})
					}
					uni.hideLoading();
					console.log('用户点击确定');
				} else if (ress.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
}

const getToken = () => {
	token = uni.getStorageSync('token')
}


// 配置管理
const config = {
  baseURL: base, // 使用原有的 base 变量
  timeout: 2 * 60 * 1000,
  defaultTenantId: '0',
  basicAuth: 'Basic YnlzYy1jbG91ZDpieXNjQDEyMzQ1Ng==',
}

// 请求队列管理
const pendingRequests = new Map()

// 添加取消请求方法
const cancelRequest = (requestId) => {
  const request = pendingRequests.get(requestId)
  if (request && request.abort) {
    request.abort()
    pendingRequests.delete(requestId)
  }
}

// 生成请求唯一键
const generateRequestKey = (url, param, method) => {
  return `${method}_${url}_${JSON.stringify(param)}`
}

// 统一错误处理
const errorMessages = {
  400: '参数错误',
  500: '服务错误',
}

const showErrorModal = (content) => {
  uni.showModal({
    title: '错误',
    confirmText: "确定",
    content,
    showCancel: false,
    success: () => {}
  })
}

const handleHttpError = (res) => {
  const statusCode = res.data ? res.data.code : res.statusCode
  const errorMessage = errorMessages[statusCode]
  if (errorMessage) {
    showErrorModal(errorMessage)
  }
  console.log('fail报错', res)
}

// 处理请求方法
const resolveMethod = (method) => {
  const methodMap = {
    POST_FORM: 'POST',
    OTHER: 'POST',
    OTHERGET: 'GET'
  }
  return methodMap[method] || method
}

// 处理请求头
const resolveHeaders = (urlObject) => {
  const headers = {
    'TenantId': config.defaultTenantId
  }

  if (urlObject.name === 'getToken') {
    headers['Authorization'] = config.basicAuth
  } else if (urlObject.name !== 'login') {
    getToken() // 保持原有的 token 获取逻辑
    headers['Authorization'] = 'Bearer ' + token
  }

  // 处理 content-type
  if (['POST', 'PUT', 'PATCH'].includes(urlObject.method)) {
    headers['content-type'] = 'application/json'
  } else if (urlObject.method === 'POST_FORM') {
    headers['content-type'] = 'application/x-www-form-urlencoded'
  }

  return headers
}

// 处理 URL
const resolveUrl = (urlObject, param) => {
  let url = config.baseURL + urlObject.path
  if (['OTHER', 'OTHERGET'].includes(urlObject.method)) {
    url += `/${Object.values(param).join('/')}`
  }
  return url
}

// 主请求函数
const request = (urlObject, param, success, fail) => {
  const url = resolveUrl(urlObject, param)
  const method = resolveMethod(urlObject.method)
  // 只有传入 requestId 的请求才会被追踪
  const requestId = param.requestId || null
  
  const option = {
    url,
    method,
    data: param,
    timeout: config.timeout,
    header: resolveHeaders(urlObject),

    success: (res) => {
      // 如果没有 requestId，使用原来的逻辑
      if (!requestId) {
        res = res.data
        if (res.code === "S00000") {
          success(res.data)
        } else {
          returnFail(res)
          fail && fail(res)
        }
        return
      }

      // 有 requestId 的请求使用竞态处理逻辑
      if (pendingRequests.has(requestId)) {
        pendingRequests.delete(requestId)
        
        res = res.data
        if (res.code === "S00000") {
          success(res.data)
        } else {
          returnFail(res)
          fail && fail(res)
        }
      }
    },

    fail: (res) => {
      if (!requestId) {
        handleHttpError(res)
        fail && fail(res)
        return
      }

      if (pendingRequests.has(requestId)) {
        pendingRequests.delete(requestId)
        handleHttpError(res)
        fail && fail(res)
      }
    },

    complete: () => {
      if (requestId) {
        pendingRequests.delete(requestId)
      }
    }
  }

  try {
    const task = uni.request(option)
    // 只有有 requestId 的请求才会被存储
    if (requestId) {
      pendingRequests.set(requestId, task)
    }
    return requestId
  } catch (error) {
    if (requestId) {
      pendingRequests.delete(requestId)
    }
    handleHttpError(error)
    fail && fail(error)
    return requestId
  }
}

const uploadRequest = (urlObject, filePath, success, fail, formData) => {
	getToken()
	let option = {
		// url: 'http://192.168.3.183:2009/app/attachment/picture/upload-image', //仅为示例，非真实的接口地址
		url: base + urlObject.path, //仅为示例，非真实的接口地址
		filePath: filePath,
		formData: formData,
		name: 'file',
		header: {
			'Authorization': 'Bearer ' + token,
			'TenantId': '0'
		},
		// formData: {
		//   'user': 'test'
		// },
		success: (res) => {
			console.log(res)
			res = res.data
			if (typeof res === 'string') {
				console.log(res)
				res = JSON.parse(res)
			}
			if (Number(res.code) === 200) {
				success(res)
			} else {
				returnFail(res)
			}
		},
		fail: (res) => {
			fail(res)
		}
	}
	uni.uploadFile(option)
}

const requestTest = (urlObject, param, resolve, reject) => {

	return new Promise((resolve, reject) => {
		let header = {}
		if (urlObject.name !== 'login') {
			getToken()
			header = {
				'Authorization': 'Bearer ' + token,
				'TenantId': '0'
			}
		}
		let option = {
			url: base + urlObject.path, //仅为示例，并非真实接口地址。
			method: urlObject.method,
			data: param,
			timeout: 2 * 60 * 1000,
			success: (res) => {
				resolve(res)
			},
			fail: (res) => {
				// 页面中弹框显示失败
				uni.showToast({
					title: '请求接口失败'
				})
				// 返回错误消息
				reject(err)
			}
		}
		if (['POST', 'PUT', 'PATCH'].indexOf(urlObject.method) > -1) {
			header['content-type'] = 'application/json'
		} else if ('POST_FORM' === urlObject.method) {
			header['content-type'] = 'application/x-www-form-urlencoded'
			option.method = 'POST'
		}
		option['header'] = header

		// 封装主体：网络请求
		uni.request(option)
	})

}

// 只使用一种导出方式
const requestModule = {
  request,
  uploadRequest,
  requestTest,
  cancelRequest
}

// 使用 default 导出
export default requestModule